package org.rency.common.trigger.schedule;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.quartz.SchedulerListener;
import org.quartz.Trigger;
import org.rency.common.trigger.listeners.DaemonTriggerListener;
import org.rency.common.trigger.schedule.repository.DaemonTaskTriggerRepository;
import org.rency.common.trigger.service.ScheduleService;
import org.rency.common.trigger.util.TriggerDict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

public class DaemonSchedulerFactoryBean extends SchedulerFactoryBean implements ApplicationContextAware,InitializingBean {

	private static final Logger logger = LoggerFactory.getLogger(DaemonSchedulerFactoryBean.class);
	
	@Resource(name="scheduleService")
	private ScheduleService scheduleService;
	
	@Resource(name="daemonTaskTriggerRepository")
	private DaemonTaskTriggerRepository daemonTaskTriggerRepository;
	
	@Resource(name="daemonSchedulerListener")
	private SchedulerListener schedulerListener;
	
	@Resource(name="daemonTriggerListener")
	private DaemonTriggerListener daemonTriggerListener;
	
    private boolean available;
    
    @Override
    public void afterPropertiesSet() throws Exception {
    	scheduleService.setSchedulerAvailable(available);
    	logger.info("准备启动定时任务队列[{}],开关状态为:[{}].",TriggerDict.DAEMON_SCHEDULER_NAME,available == true ? "打开" : "关闭");
        if(!available){
            logger.info("定时任务[{}]为关闭状态，无须初始化。",TriggerDict.DAEMON_SCHEDULER_NAME);
            return;
        }
        scheduleService.initDataBaseTable();
        daemonTaskTriggerRepository.initStatus();
        
        // 获取触发器
		List<Trigger> triggerList = scheduleService.loadEnableTriggers();
        if (CollectionUtils.isEmpty(triggerList)) {
        	logger.info("定时任务[{}]装载无数据，无须执行。",TriggerDict.DAEMON_SCHEDULER_NAME);
        	return;
        }
        Trigger[] triggerArray = new Trigger[triggerList.size()];
        int count = 0;
        for (Trigger trigger : triggerList) {
            triggerArray[count] = trigger;
            count++;
        }

        // 设置触发器列表
        super.setTriggers(triggerArray);
        
        // 执行父类设置
        super.setSchedulerName(TriggerDict.DAEMON_SCHEDULER_NAME);
        super.setSchedulerListeners(schedulerListener);
        super.setGlobalTriggerListeners(daemonTriggerListener);
        super.afterPropertiesSet();        
    }
    
    public void setAvailable(boolean available) {
        this.available = available;
    }
}